<?php
class Catalog_Model_Tree extends Zen_Tree {
	public function __construct() {
	    $table = new Zend_Db_Table ( 'catalog_tree' );
		$this->table = $table;
		$types=array(
			'root'=>array(
						'icon'=>'/cms/res/icons/drive.png',
						'label'=>'Каталог товаров',
						'valid_children'=>array('folder'),
						'start_drag'=>false,
						'move_node'=>false,
						'delete_node'=>false,
						'remove'=>false
						),
			'folder'=>array(
						'table'=>'catalog_folder',
						'label'=>'раздел',
						'icon'=>'/cms/res/icons/folder.png',
						'form' => 'Catalog_Form_Folder', 
						'view' => 'form.phtml', 
						'valid_children'=>array('wares'),
						'start_drag'=>true,
						'move_node'=>true,
						'delete_node'=>true,
						'remove'=>true
						),
			'wares'=>array(
						'table'=>'catalog_wares',
						'label'=>'товар',
						'icon'=>'/cms/res/icons/cart.png',
						'form' => 'Catalog_Form_Wares', 
						'view' => 'form.phtml', 
						'valid_children'=>'none',
						'start_drag'=>true,
						'move_node'=>true,
						'delete_node'=>true,
						'remove'=>true
						)						
		);
		$this->setTypes ( $types );
		
		$this->columns=array(
			'types'=>array('wares'),
			'columns'=>array(
						array('width'=> '600','header'=>' '),
						array('cellClass'=> 'col_date', 'value'=> 'price', 'width'=>200, 'header'=> 'Цена')
			));
		
		
	}
	
	public function getSelectData(){
		$res=array(0=>'Не выбрано');
		$tree = $this->select()
					->setDepth(2)
					->setParentId(0)
					->setColumns(array(
						'tree' => array('id','type','parent_id') ,
						'folder' 	=> array('label', 'alias') ,
						'wares' => array('label', 'alias',) ,
					))
					->setOrder('tree.left')
					->getData();
		if (! $tree)
			return false;
		$disabled=array();
		foreach ($tree as $item) {
			$label = preg_replace('/[\',\",\«,\»]/ui', "", $item['label']);
			if($item['type']=='folder'){
				$disabled[]=$item['id'];
			} else {
				$label = '------> ' . $label;
			}
			$res[$item['id']] = $label;
			
		}
		return array('data'=>$res,'disabled'=>$disabled);
	}
	
	public function generateWaresUrl($id){
		$getItem=$this->table->select()->where('`id`='.$id)->query()->fetchAll();
		if(isset($getItem[0]['id'])) {
			$parents=$this->table->select()->where('`left`<=?',$getItem['0']['left'])->where('`right`>=?',$getItem['0']['right'])->where('`level`=1')->order('left')->query()->fetchAll();
			if(isset($parents[0]['id'])){
				$folder=new Catalog_Model_Folder();
				$folder=$folder->getOne("`id`='".$parents[0]['id']."'");
				return $folder;
			}
		}
	}
	
	public function getFolderByAlias($alias) {
		if (! $alias)
			return false;
		$res = $this->select()
					->setDepth(0)
					->setColumns(array('tree'=>array('id','parent_id'),'folder'=>array('label','alias')))
					->setOrder('tree.left')
					->getOne("tree.type='folder' and folder.alias='".$alias."'");
		return $res;
	}
	
	public static function compare_prices($a,$b) {
     if (($a['price']  > $b['price'])||(($b['top'])))
         return 1;
     elseif ($a['price']  < $b['price'])
         return -1;
     else
         return 0;
	}
	
	public function getItemListByAlias($alias) {
		$folder = $this->getFolderByAlias($alias);
		if (! $folder)
			return false;
		$res = $this->select()
					->setDepth(0)
					->setParentId($folder['id'])
					->setColumns(array('tree'=>array('id','parent_id'),'wares'=>array('label','images','mech','price','top','stripe','alias','gab_width','gab_length','sleep_width','sleep_length','alias')))
					->setOrder('tree.left')
					->getData("tree.type='wares'");
		if (! $res) 
			return false; 
		usort($res, array('Catalog_Model_Tree', 'compare_prices'));
		$model = new Mech_Model_Item();
		$mech_list = $model->getList();
		$mech_array = array();
		$mech_key_array = array();
		foreach ($mech_list as $item) {
			$mech_key_array[] = $item['id'];
		 	$mech_array[$item['id']] = $item;
		}
		foreach ($res as $key=>$value) {
			if ($value['mech']) {
				if (in_array($value['mech'], $mech_key_array)) {
					$mech =  $mech_array[$value['mech']];
					$res[$key]['mech'] = $mech;
				} 
			}
		} 
		return $res;
	}
	
	public function getFolderById($id) {
		if (! $id)
			return false;
		$res = $this->select()
					->setDepth(0)
					->setColumns(array('tree'=>array('id','parent_id'),'folder'=>array('label','alias')))
					->setOrder('tree.left')
					->getOne("tree.type='folder' and folder.id='".$id."'");
		return $res;
	}
	
	public function getItemByAlias($alias) {
		
		if (! $alias)
			return false;
		$res = $this->select()
					->setDepth(0)
					->setColumns(array('tree'=>array('id','parent_id'),'wares'=>array('label','images','mech','price','top','stripe','alias','gab_width','gab_length','sleep_width','sleep_length','alias','near','file3d','info','sizes','sit_height','sit_depth')))
					->setOrder('tree.left')
					->getOne("tree.type='wares' and alias='".$alias."'");
		if (! $res)
			return false;
			
		//Привязать родителя
		$parent = $this->getFolderById($res['parent_id']);
		if ($parent)
			$res['parent'] = $parent;
			
		//Привязать механизм
		$model = new Mech_Model_Item();
		$mech = $model->getMechById($res['mech']); 
		if ($mech) 
			$res['mech'] = $mech;
			
		//Привязать рекомендуем
		$near = null;
		if ( $res['near'] ) {
			$near=unserialize($res['near']);
			if ($near) {
				if(count($near)>0){
					$where = "`id` IN(".$near.")";
					$item_model = new Zen_List('catalog_wares');
					$near = $item_model->select()->getData($where);
				}
			}
		}
		$res['near'] = ($near) ? $near : false;
		return $res;
	}
	
	public function afterChange() {
		$this->updatePath ();
	}
	
	protected function updatePath() {
		
		$data = $this->select ()->setColumns ( array ('tree' => array ('id', 'parent_id', 'left', 'right','level','type' ), 'folder' => array ('alias', 'label','aliasfull' ), 'wares' => array ('alias', 'label','aliasfull' )) )->setOrder('tree.left')->setDepth ( 0 )->getData ();
		$alias = array();
		
		$types=$this->getTypes();
		foreach ( $data as $node ) {
			ksort( $alias, SORT_NUMERIC );
			$level = $node['level'];
			if ( isset($alias[$level]) ) {
				$count = count($alias);
				for ($i = $level; $i<=$count; $i++ ) {
					unset ($alias[$i]);
				}
			}
			$alias[$level]=$node['alias'];
			$aliasfull="/".implode('/', $alias).'/';
			$ItemModel = $types[$node['type']] ['model'];
			$aliasfull=preg_replace('/\\/\\//', '/', $aliasfull);
			if($node['aliasfull']!='/shop'.$aliasfull){
				$res = $ItemModel->update($node['id'],array('aliasfull'=>'/shop'.$aliasfull));
			}	
		}
	}
	
}